package com.finals.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Path.Direction;
import android.graphics.Path.Op;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

public class RoundImageView extends ImageView {

	Path mPath;

	public RoundImageView(Context context) {
		super(context);
		InitPath(context, null);
	}

	public RoundImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		InitPath(context, attrs);
	}

	public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		InitPath(context, attrs);
	}

	private void InitPath(Context context, AttributeSet attrs) {
		mPath = new Path();
		CloseHardWare();
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		if (changed) {
			mPath.reset();
			float x = getWidth() / 2;
			if (x % 2 > 0) {
				x = x - 1;
			}

			float y = getHeight() / 2;
			if (y % 2 > 0) {
				y = y - 1;
			}

			float radius = getWidth() / 2 - 1 - getPaddingLeft();
			if (radius % 2 > 0) {
				radius = radius - 1;
			}

			mPath.addCircle(x, y, radius, Direction.CCW);
			mPath.close();
		}
		super.onLayout(changed, left, top, right, bottom);
	}

	@SuppressLint("NewApi")
	@Override
	public void draw(Canvas canvas) {
		canvas.save();
		canvas.clipPath(mPath, android.graphics.Region.Op.INTERSECT);
		super.draw(canvas);
		canvas.restore();
	}

	@SuppressLint("NewApi")
	public void CloseHardWare() {
		try {
			if (android.os.Build.VERSION.SDK_INT >= 11) {
				setLayerType(LAYER_TYPE_SOFTWARE, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
